<template>
  <el-dialog
    :title="title"
    :close-on-click-modal="false"
    :visible.sync="visible"
    width="700px"
  >
    <el-form
      :model="accountForm"
      :rules="accountFormRules"
      ref="accountForm"
      label-width="100px"
    >
      <el-row>
        <el-col :span="12">
          <el-form-item label="姓名：" prop="name">
            <el-input
              v-model="accountForm.name"
              placeholder="请输入姓名"
              clearable
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="用户名：" prop="mobile">
            <el-input
              v-model="accountForm.mobile"
              placeholder="请输入用户名"
              clearable
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="部门：" prop="department_id">
            <el-cascader
              :options="departmentList"
              :show-all-levels="false"
              :props="{ checkStrictly: true }"
              v-model="accountForm.department_id"
              placeholder="请选择所属部门"
              clearable
            ></el-cascader>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="用户类型" prop="user_type">
            <nice-select
              v-model="accountForm.user_type"
              placeholder="请选择用户类型"
              clearable
              :options="selectArr.user_type"
            ></nice-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="角色：" prop="nice_role_id">
            <nice-select
              v-model="accountForm.nice_role_id"
              placeholder="请选择角色"
              clearable
              :multiple="true"
              :options="roleList"
            ></nice-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="状态：" prop="status">
            <nice-select
              v-model="accountForm.status"
              placeholder="请选择账户状态"
              clearable
              :options="accountStatus"
              :disabled="mode === 'add'"
            ></nice-select>
          </el-form-item>
        </el-col>
      </el-row>
      <!-- <el-row>
              <el-col :span="12">
                <el-form-item label="岗位：" prop="position_id">
                       <el-cascader
                          :options="positionList"
                          v-model="accountForm.position_id"
                          :show-all-levels="false"
                          :props="{ checkStrictly: true }"
                          placeholder="请选择岗位"
                          clearable
                        ></el-cascader>
                  </el-form-item>
              </el-col>
            </el-row> -->
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false" size="small">取消</el-button>
      <el-button
        type="primary"
        @click="dataFormSubmit"
        size="small"
        v-preventReClick
        >确定</el-button
      >
    </span>
  </el-dialog>
</template>

<script>
import { addAccount, editUserAccount } from '@/api/user'
import { queyEnumByTableName } from '@/api/api'
export default {
  data () {
    return {
      visible: false,
      selectArr: { user_type: [] },
      accountForm: {
        name: '',
        mobile: '',
        department_id: [],
        position_id: [],
        nice_role_id: [],
        status: '',
        user_type: ''
      },
      title: '',
      accountStatus: [
        { value: 0, label: '已关闭' },
        { value: 1, label: '已开通' }
      ],
      user_id: '',
      accountFormRules: {
        name: [{ required: true, message: '姓名不能为空', trigger: 'blur' }],
        mobile: [
          { required: true, message: '用户名不能为空', trigger: 'blur' }
        ],
        department_id: [
          { required: true, message: '请选择所属部门', trigger: 'change' }
        ],
        position_id: [
          { required: true, message: '请选择岗位', trigger: 'change' }
        ],
        nice_role_id: [
          { required: true, message: '请选择所属角色', trigger: 'change' }
        ],
        status: [{ required: true, message: '请选择状态', trigger: 'change' }],
        user_type: [
          { required: true, message: '请选择用户类型', trigger: 'change' }
        ]
      }
    }
  },
  props: {
    mode: String,
    roleList: {
      type: Array,
      default: function () {
        return []
      }
    },
    departmentList: {
      type: Array,
      default: function () {
        return []
      }
    },
    positionList: {
      type: Array,
      default: function () {
        return []
      }
    }
  },
  methods: {
    init (row) {
      this.visible = true
      this.$nextTick(() => {
        this.$refs['accountForm'].resetFields()
        this.title = this.mode === 'edit' ? '编辑账号' : '新增账号'
        this.accountForm.status = this.mode === 'add' ? 1 : ''
        this.queyEnumByTableName(row)
      })
    },
    async queyEnumByTableName (row) {
      let res = await queyEnumByTableName({ tableName: 'sys_user' })
      if (res[0]) {
        return
      }
      let arr = res[1].data
      Object.keys(this.selectArr).forEach(item => {
        for (let i = 0; i < arr.length; i++) {
          if (arr[i].fieldName === item) {
            this.selectArr[item] = arr[i].child
          }
        }
      })
      this.selectArr = JSON.parse(
        JSON.stringify(this.selectArr)
          .split('display_value')
          .join('label')
          .split('child')
          .join('children')
          .split('real_value')
          .join('value')
      )
      if (row) {
        this.accountForm.name = row.name
        this.accountForm.mobile = row.account
        this.accountForm.department_id =
          this.$familyTree(row.department_id, this.departmentList) || []
        this.accountForm.position_id =
          this.$familyTree(row.position_id, this.positionList) || []
        this.accountForm.status = row.open_status
        this.user_id = row.user_id
        this.accountForm.nice_role_id = row.role ? row.role.split(',') : []
        this.accountForm.user_type = row.user_type ? row.user_type : '' // 用户类型回显
      }
    },
    // 表单提交
    dataFormSubmit () {
      this.$refs['accountForm'].validate(valid => {
        if (valid) {
          this.submit()
        }
      })
    },
    async submit () {
      let departmentLength =
        this.accountForm.department_id && this.accountForm.department_id.length
          ? this.accountForm.department_id.length - 1
          : 0
      let postionsLength =
        this.accountForm.position_id && this.accountForm.position_id.length
          ? this.accountForm.position_id[
              this.accountForm.position_id.length - 1
            ]
          : ''
      let res =
        this.mode === 'add'
          ? await addAccount({
            'sys_user.username': this.accountForm.mobile,
            'sys_user.status': this.accountForm.status,
            'nice_user_base.real_name': this.accountForm.name,
              // 'nice_user_base.mobile': this.accountForm.mobile,
            'nice_inner_user.department_id': this.accountForm.department_id[
                departmentLength
              ],
            'nice_inner_user.position_id': postionsLength,
            'nice_inner_user.status': 0,
            'nice_user_role.array': this.accountForm.nice_role_id.map(ele => {
              return { nice_role_id: ele }
            }),
            'sys_user.user_type': this.accountForm.user_type,
            'nice_user_base.user_type': this.accountForm.user_type
          })
          : await editUserAccount({
            'sys_user.username': this.accountForm.mobile,
            'sys_user.status': this.accountForm.status,
            'sys_user.user_id': this.user_id,
              // 'nice_user_base.mobile': this.accountForm.mobile,
            'nice_user_base.real_name': this.accountForm.name,
            'nice_user_base.sys_user_id': this.user_id,
            'nice_inner_user.department_id': this.accountForm.department_id[
                this.accountForm.department_id.length - 1
              ],
            'nice_inner_user.position_id': this.accountForm.position_id[
                this.accountForm.position_id.length - 1
              ],
            'nice_inner_user.user_id': this.user_id,
            'nice_user_role.enable': '1',
            'nice_user_role.sys_user_id': this.user_id,
            'nice_user_role.array': this.accountForm.nice_role_id.map(ele => {
              return { nice_role_id: ele, sys_user_id: this.user_id }
            }),
            'sys_user.user_type': this.accountForm.user_type, // 用户类型
            'nice_user_base.user_type': this.accountForm.user_type // 用户类型
          })
      if (res[0]) {
        return
      }
      let data = res[1]
      if (data && data.code === 0) {
        this.$message({
          message: `${this.mode === 'edit' ? '编辑' : '新增'}成功`,
          type: 'success',
          duration: 1500,
          onClose: () => {
            this.visible = false
            this.$emit('refreshDataList')
          }
        })
      } else {
        this.$message.error(data.msg)
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.el-scrollbar .el-scrollbar__view .el-select-dropdown__item {
  height: auto;
  max-height: 274px;
  padding: 0;
  overflow: hidden;
  overflow-y: auto;
}
.el-select-dropdown__item.selected {
  font-weight: normal;
}
// ul li >>>.el-tree .el-tree-node__content{
//   height:auto;
//   padding: 0 20px;
// }
.el-tree-node__label {
  font-weight: normal;
}
// ？？？
// .el-tree >>>.is-current .el-tree-node__label{
//   color: #409EFF;
//   font-weight: 700;
// }
// .el-tree >>>.is-current .el-tree-node__children .el-tree-node__label{
//   color:#606266;
//   font-weight: normal;
// }
.el-tabs--left .el-tabs__header.is-left {
  margin-right: 40px !important;
}
.select_input {
  margin: 10px 5%;
  width: 90%;
}
</style>
